<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="40%">
    <div class="data-form-wrap">
      <el-form ref="dataForm" class="dataForm" :model="forms" :rules="rules" label-width="120px">
        <el-form-item label="上级机构" prop="parentId">
          <treeselect
            v-model="forms.parentId"
            :options="orgTreeData"
            :normalizer="normalizer"
            :disabled="disabled"
            :load-options="loadOptions"
            no-children-text="暂无下级机构"
            loading-text="数据加载中"
            placeholder="选择组织机构"
          >
            <div slot="option-label" slot-scope="{ node }">
              {{ node.raw.name }}
            </div>
            <div slot="value-label" slot-scope="{ node }">
              <span>{{ node.raw.name }}</span>
            </div>
          </treeselect>
        </el-form-item>
        <el-form-item label="机构名称" prop="orgName">
          <el-input v-model.trim="forms.orgName" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="机构简称" prop="shortName">
          <el-input v-model.trim="forms.shortName" placeholder="请输入机构简称" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="forms.category" placeholder="请选择机构类别" style="width: 100%">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织形式" prop="orgForm">
          <el-select v-model="forms.orgForm" placeholder="请选择组织形式" style="width: 100%">
            <el-option
              v-for="item in getOrgFormListData"
              :key="item.itemValue"
              :label="item.itemLabel"
              :value="item.itemValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序 " prop="sortNum">
          <el-input type="number" @input="validateInput" v-model="forms.sortNum" />
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitHandle">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addOrUpdOrg, getOrganizationById } from '@/api/orgManage'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import { organizationTree } from '@/api/userManage'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'Edit',
  components: {
    Treeselect
  },
  props: {
    getOrgFormListData: {
      type: Array,
      require: true,
      default: () => []
    }
  },
  data () {
    return {
      categoryList: [
        {
          id: 1,
          name: '内部'
        },
        {
          id: 2,
          name: '外部'
        }
      ],
      orgTreeData: [],
      title: '',
      dialogVisible: false,
      disabled: false,
      forms: {},
      rules: {
        category: [{ required: true, message: '类别不能为空', trigger: 'change' }],
        orgName: [
          { required: true, message: '机构名称不能为空', trigger: 'blur' },
          { max: 50, message: '不能超过50个字符', trigger: 'blur' }
        ],
        shortName: [
          { required: true, message: '机构简称不能为空', trigger: 'blur' },
          { max: 50, message: '不能超过50个字符', trigger: 'blur' }
        ],
        orgForm: [
          { required: true, message: '组织形式不能为空', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    validateInput () {
      this.forms.sortNum = this.forms.sortNum.replace(/[^\d]/g, '') // 使用正则表达式去除非数字字符
      if (this.forms.sortNum === '' || this.forms.sortNum === '0') {
        this.forms.sortNum = 1 // 默认设置为1或任何你认为合适的默认正整数
      } else if (this.forms.sortNum > 99999) {
        this.forms.sortNum = 99999
      }
    },
    normalizer (node) {
      return {
        id: node.id,
        label: node.name,
        children: node.sub
      }
    },
    async loadOptions ({ action, parentNode, callback }) {
      console.log('load')
      if (action === LOAD_CHILDREN_OPTIONS) {
        const res = await organizationTree({ parent: parentNode.id })
        const arr = res.data.map((v) => {
          if (v.childNum > 0) {
            v.sub = null
            return v
          } else {
            return v
          }
        })
        this.$set(parentNode, 'sub', arr)
        callback()
      }
    },
    async open (str, row) {
      this.dialogVisible = true
      this.disabled = false
      this.orgTreeData = []
      this.organizationTreeData(row)
      console.log(str, row, ' str')
      if (str === 'add') {
        this.title = '新增组织机构'
        this.forms = {
          parentId: '0',
          category: '',
          orgName: '',
          shortName: '',
          orgForm: '',
          sortNum: 1
        }
      } else if (str === 'update') {
        this.title = '修改组织机构'
        this.disabled = true
        this.getOrganizationByIdData(row)
      } else {
        this.title = '新增下级机构'
        this.disabled = true
        this.orgTreeData = [
          {
            name: '根节点',
            id: '0',
            sub: [
              {
                name: row.name,
                id: row.id
              }
            ]
          }
        ]
        this.forms = {
          parentId: row.id,
          category: '',
          orgName: '',
          shortName: '',
          orgForm: '',
          sortNum: 1
        }
      }
    },
    async getOrganizationByIdData (row) {
      const res = await getOrganizationById({ id: row.id })
      console.log(res, 'ressss')
      if (res.code === 'success') {
        this.orgTreeData = [
          {
            name: '根节点',
            id: '0',
            sub: [
              {
                name: res.data.parentName,
                id: res.data.parentId
              }
            ]
          }
        ]
        this.forms = {
          parentId: !res.data.parentId ? '0' : res.data.parentId,
          id: res.data.id,
          category: res.data.category,
          orgName: res.data.orgName,
          shortName: res.data.shortName,
          orgForm: res.data.orgForm === null ? '' : res.data.orgForm,
          sortNum: res.data.sortNum
        }
      }
    },
    async organizationTreeData (row) {
      const res = await organizationTree({ parent: row?.parentId || '' })
      console.log(res, 'res')
      const arr = res.data.map((v) => {
        if (v.childNum > 0) {
          v.sub = null
          return v
        } else {
          return v
        }
      })
      this.orgTreeData = [
        {
          name: '根节点',
          id: '0',
          sub: arr
        }
      ]
    },
    async submitHandle () {
      this.$refs.dataForm.validate(async (valid) => {
        if (valid) {
          if (this.forms.parentId === '0') {
            delete this.forms.parentId
          }
          const res = await addOrUpdOrg(this.forms)
          if (res.code === 'success') {
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.$emit('getTableList')
            this.$refs.dataForm.resetFields()
          } else {
            this.$message.error(res.msg)
          }
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #fff none;
  border-radius: 4px;
  height: 300px;
  overflow-y: auto;
}
</style>
